﻿using HuiZe.education.Model;
using HuiZe.education.Resource.Controls;
using HuiZe.education.ViewModel;
using System;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using YuanCode.Control.Controls;
using Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Word;
using System.Reflection;
using Spire.Presentation;
using System.IO;
using HuiZe.education.Resource.Controls.VideoPlay;
using HuiZe.education.Common;
using HuiZe.education.View.AttendClassView;

namespace HuiZe.education.View
{
    /// <summary>
    /// ResourceView.xaml 的交互逻辑
    /// </summary>
    public partial class ShowResource : HuiZeWindow
    {
        public PlanLessonViewModel planModel { get; set; }
   
        public WebBrowser webBrowser0 { set; get; }
        public string BkType { get; set; }
        public string BkId { get; set; }
        public ShowResource()
        {
            InitializeComponent();
            this.MaxHeight = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height + 10;
            this.MaxWidth = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width + 10;
            Loaded += ResourceView_Loaded;
        }
        public ObservableCollection<ResourceCenterModel> resources { get; set; }

        private void ResourceView_Loaded(object sender, RoutedEventArgs e)
        {
            webBrowser0 = new  WebBrowser();
            //webBrowser0.ScriptErrorsSuppressed = true;

            PlanLessonViewModel planLessoniewModel = DataContext as PlanLessonViewModel;
            resCourseListChildModel obj0 =null;
            resBKCategoryCourseChildModel obj1 = null;
            ReqGroupFileListDetialModel obj2 = null;
            resBKCategoryCourseChildModel obj3 = null;
            if (BkType == "0")
            {
                obj0 = planLessoniewModel.GetResourceKcZy(BkId);
                resList.Children.Clear();
                CustomButton customButton = new CustomButton()
                {
                    Template = (ControlTemplate)FindResource("HZImageButtonTemplate"),
                    ImageSource = new BitmapImage(new Uri(obj0.cover)),
                    SourceUrl = obj0.file,
                    //MeadiaType
                    Content = obj0.resources_name,
                    Width = 100,
                    Height = 50,
                    Margin = new Thickness(0, 0, 10, 0),
                };
                customButton.Click += customButton_Click;
                resList.Children.Add(customButton);
            }
            if (BkType == "1")
            {
                obj1 = planLessoniewModel.GetResourceCenter(BkId);

                resList.Children.Clear();
               
                CustomButton customButton = new CustomButton()
                {
                    Template = (ControlTemplate)FindResource("HZImageButtonTemplate"),
                    ImageSource = new BitmapImage(new Uri(obj1.image)),
                    SourceUrl = obj1.file,
                    //MeadiaType
                    Content = obj1.resources_name,
                    Width = 80,
                    Height = 50,
                    Margin = new Thickness(0, 0, 10, 0),
                };
                customButton.Click += customButton_Click;
                resList.Children.Add(customButton);



            }
            if (BkType== "2")
            {
                obj2 = planLessoniewModel.GetResourceMySpace(BkId);

                resList.Children.Clear();

                CustomButton customButton = new CustomButton()
                {
                    Template = (ControlTemplate)FindResource("HZImageButtonTemplate"),
                    ImageSource = new BitmapImage(new Uri(obj2.file)),
                    SourceUrl = obj2.file,
                    //MeadiaType
                    Content = obj2.file_name,
                    Width = 100,
                    Height = 50,
                    Margin = new Thickness(0, 0, 10, 0),
                };
                customButton.Click += customButton_Click;

               
                resList.Children.Add(customButton);
            }

            if (BkType == "3")
            {
                obj3 = planLessoniewModel.GetMyCllection(BkId);

                resList.Children.Clear();

                CustomButton customButton = new CustomButton()
                {
                    Template = (ControlTemplate)FindResource("HZImageButtonTemplate"),
                    ImageSource = new BitmapImage(new Uri(obj3.image)),
                    SourceUrl = obj3.file,
                    //MeadiaType
                    //Content = obj3.ziyuan.resources_name,
                    Width = 100,
                    Height = 50,
                    Margin = new Thickness(0, 0, 10, 0),
                };
                customButton.Click += customButton_Click;


                resList.Children.Add(customButton);
            }



        }


        private void customButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            CustomButton customButton = sender as CustomButton;
            //string preUrl = "https://ow365.cn/?i=28004&ssl=1&n=5&furl=";
            string url = customButton.SourceUrl;
            //MediaPlayBorder.Children.Clear();



            if (url.ToString().Contains("jpg") || url.ToString().Contains("png"))
            {
                string LocalPath = DownLoadFile(url, AppDomain.CurrentDomain.BaseDirectory + "\\ConvertHtmls\\");
                webBrowser.Navigate("file:\\" + LocalPath);
            }
            else if (url.ToString().Contains("mp3") || url.ToString().Contains("mp4"))
            {

                //BdBrowser.Children.Clear();
                //VideoPlayer2 videoPlayer = new VideoPlayer2
                //{
                //    PlayUrl = url,
                //    Width = 897,
                //    Height = 568,
                //    Margin = new Thickness(20, 0, 0, 0)
                //};
                //MediaPlayBorder.Children.Add(videoPlayer);
                //string LocalPath = DownLoadFile(url, AppDomain.CurrentDomain.BaseDirectory + "\\ConvertHtmls\\");
                //videoPlayer.PlayUrl = LocalPath;
                //webBrowser.Navigate("file:\\" + LocalPath);


                //var w = new WebBrowserOverlay(this.BdBrowser);
                //var wb = w.WebBrowser;
                //var HelpUrl = "file:\\" + LocalPath;
                //wb.Navigate(HelpUrl);
            }
            else if (url.ToString().Contains("ppts") || url.ToString().Contains("ppt"))
            {
                string loadPath = PptToHtml(url, AppDomain.CurrentDomain.BaseDirectory + "\\ConvertHtmls\\");
                webBrowser.Navigate("file:\\" + @loadPath);

                //var w = new WebBrowserOverlay(this.BdBrowser);
                //var wb = w.WebBrowser;
                //var HelpUrl = "file:\\" + @loadPath;
                //wb.Navigate(new System.Uri(HelpUrl));

                //webBrowser.Width = 876;
                //webBrowser.Height = 694;
                //MediaPlayBorder.Children.Add(webBrowser0);
            }
            else if (url.ToString().Contains("doc") || url.ToString().Contains("docx"))
            {
                string loadPath = PreviewWord(url, AppDomain.CurrentDomain.BaseDirectory + "\\ConvertHtmls\\");
                webBrowser.Navigate("file:\\" + @loadPath);

                //var w = new WebBrowserOverlay(this.BdBrowser);
                //var wb = w.WebBrowser;
                //var HelpUrl = "file:\\" + @loadPath;
                //wb.Navigate(new System.Uri(HelpUrl));

                //webBrowser11.Width = 876;
                //webBrowser11.Height = 694;
                //MediaPlayBorder.Children.Add(webBrowser0);
            }
            else if (url.ToString().Contains("xlsx") || url.ToString().Contains("xls"))
            {
                string loadPath = PreviewExcel(url, AppDomain.CurrentDomain.BaseDirectory + "\\ConvertHtmls\\");
                webBrowser.Navigate("file:\\" + @loadPath);

                //var w = new WebBrowserOverlay(this.BdBrowser);
                //var wb = w.WebBrowser;
                //var HelpUrl = "file:\\" + @loadPath;
                //wb.Navigate(new System.Uri(HelpUrl));
                //webBrowser.Width = 876;
                //webBrowser.Height = 694;
                //MediaPlayBorder.Children.Add(webBrowser0);
            }
            else
            {



            }







        }


        private string DownLoadFile(string url, string savepath)
        {
            string extention = Path.GetExtension(url);
            string FileName = Path.GetFileNameWithoutExtension(url);
            string downloadpath = savepath + "\\" + FileName + extention;
            WebApiHelper.Download(url, downloadpath);

            return downloadpath;


        }
        private void close_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            this.Close();
        }

      

        private void SourceTree_PreviewMouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
          
                
        }









        /// 预览Excel
        /// </summary>
        /// <param name="physicalPath">解码的地址</param>
        /// <param name="url"></param>
        public string PreviewExcel(string url, string savepath)
        {
            var resultUrl = string.Empty;
            var serverUrl = string.Empty;

            string extention = Path.GetExtension(url);
            string FileName = Path.GetFileNameWithoutExtension(url);
            try
            {
                string downloadpath = savepath + "\\" + FileName + extention;
                WebApiHelper.Download(url, downloadpath);



                Microsoft.Office.Interop.Excel.Application application = null;
                //参数
                Workbook workbook = null;
                application = new Microsoft.Office.Interop.Excel.Application();
                object missing = Type.Missing;
                object trueObject = true;
                application.Visible = false;
                application.DisplayAlerts = false;
                workbook = application.Workbooks.Open(downloadpath, missing, trueObject, missing, missing, missing,
                   missing, missing, missing, missing, missing, missing, missing, missing, missing);
                object format = XlFileFormat.xlHtml;
                string htmlName = Path.GetFileNameWithoutExtension(downloadpath) + ".html";
                String outputFile = Path.GetDirectoryName(savepath) + "\\" + htmlName;
                workbook.SaveAs(outputFile, XlFileFormat.xlHtml, null, null, false, false,
                   XlSaveAsAccessMode.xlNoChange, null, null, null, null, null);

                workbook.Close();
                application.Quit();
                resultUrl = Path.GetDirectoryName(url) + "\\" + htmlName;
                var lastUrl = Path.GetFileName(resultUrl);
                //resultUrl = ConfigurationManager.AppSettings["ResultUrl"] + lastUrl;
                //serverUrl = ConfigurationManager.AppSettings["ServerUrl"];

                return outputFile;
            }
            catch (Exception ex)
            {
                //this.Write(ex);
            }
            return serverUrl + resultUrl;
        }
        /// 预览Word（HtmL类型）
        /// </summary>
        /// <param name="physicalPath"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public string PreviewWord(string url, string savepath)
        {

            var resultUrl = string.Empty;
            var serverUrl = string.Empty;
            object outputFile1 = new object();
            object missing1 = new object();

            string extention = Path.GetExtension(url);
            string FileName = Path.GetFileNameWithoutExtension(url);


            //检查doc 是否被实例化
            var idd = 0;
            var ss = 1;
            try
            {
                string downloadpath = savepath + "\\" + FileName + extention;
                WebApiHelper.Download(url, downloadpath);



                Microsoft.Office.Interop.Word._Application application = null;
                Microsoft.Office.Interop.Word._Document doc = null;
                application = new Microsoft.Office.Interop.Word.Application();
                //参数
                object missing = Missing.Value;
                object trueObject = true;
                application.Visible = false;
                application.DisplayAlerts = WdAlertLevel.wdAlertsNone;
                object physicalPathObj = downloadpath;
                //实例化
                doc = application.Documents.Open(ref physicalPathObj, ref missing, ref trueObject, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
                string htmlName = Path.GetFileNameWithoutExtension(url) + ".html";
                object outputFile = Path.GetDirectoryName(savepath) + "\\" + htmlName;
                object format = WdSaveFormat.wdFormatHTML;
                outputFile1 = outputFile;
                missing1 = missing;
                idd = doc.DocID;
                ss = doc.CompatibilityMode;
                //转换并保存
                doc.SaveAs(ref outputFile, ref format, ref missing, ref missing, ref missing,
                                      ref missing, XlSaveAsAccessMode.xlNoChange, ref missing,
                                      ref missing, ref missing, ref missing, ref missing);
                doc.Close();
                application.Quit();
                //返回137的路径                  
                resultUrl = Path.GetDirectoryName(url) + "\\" + htmlName;
                var lastUrl = Path.GetFileName(resultUrl);

                return outputFile.ToString();
                //resultUrl = ConfigurationManager.AppSettings["ResultUrl"] + lastUrl;
                //serverUrl = ConfigurationManager.AppSettings["ServerUrl"];
            }
            catch (Exception ex)
            {
                //this.Write(ex, $"{outputFile1}+{missing1}+{idd.ToString()}+{ss.ToString()}+{physicalPath}");

            }
            return serverUrl + resultUrl;
        }
        #region  预览ppt（使用Presentation插件）
        /// <summary>
        /// ppt转html
        /// </summary>
        /// <returns></returns>
        public string PptToHtml(string url, string savepath)
        {
            var resultUrl = string.Empty;
            var serverUrl = string.Empty;
            string extention = Path.GetExtension(url);
            string FileName = Path.GetFileNameWithoutExtension(url);
            string htmlName = Path.GetFileNameWithoutExtension(url) + ".html";
            String outputFile = Path.GetDirectoryName(savepath) + "\\" + htmlName;
            //实例化Presentation类，加载文件
            Spire.Presentation.Presentation ppt = new Spire.Presentation.Presentation();
            try
            {
                string downloadpath = savepath + "\\" + FileName + extention;
                WebApiHelper.Download(url, downloadpath);

                ppt.LoadFromFile(downloadpath);
                ppt.SaveToFile(outputFile, FileFormat.Html);

                //打开文件

                //保存文件为HTML

            }//`在这里插入代码片`
            catch (Exception ex)
            {
                //this.Write(ex);
            }
            //得到返回的html地址
            resultUrl = Path.GetDirectoryName(savepath) + "\\" + htmlName;
            var lastUrl = Path.GetFileName(resultUrl);
            //resultUrl = ConfigurationManager.AppSettings["ResultUrl"] + lastUrl;
            //serverUrl = ConfigurationManager.AppSettings["ServerUrl"];
            return outputFile;


        }

        private void exitAddStu_Click(object sender, RoutedEventArgs e)
        {

            bg_videoPlay.Visibility = Visibility.Collapsed;
            bg_webPlay.Visibility = Visibility.Visible;
            
        }
        #endregion




        //private void button1_Click(object sender, EventArgs e)
        //{
        //    string wordPath = basePath + "\\File\\3.pptx";
        //    string savePath = basePath + "\\3.html";
        //    string prePath = PptToHtml(wordPath, savePath);
        //    webBrowserDoc.Navigate(prePath);
        //}




    }


}
